package com.spzx.common.rabbit.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

@Slf4j
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallbacks();
    }

    private void setupCallbacks() {

        //生产者确认机制
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                System.out.println("消息发送失败:" + cause);
            } else {
                System.out.println("消息发送成功:" );
            }
        });

        //生产者退回机制
        //rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(returned -> {
            System.out.println("消息：" + returned.getMessage());
            System.out.println("描述：" + returned.getReplyText());
            System.out.println("状态：" + returned.getReplyCode());
            System.out.println("路由：" + returned.getRoutingKey());
            System.out.println("交换机：" + returned.getExchange());
        });

    }
}

